package com.shengchang.hu.supervision.UI;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.posapi.PosApi;
import android.posapi.PosApi.OnCommEventListener;
import android.posapi.PrintQueue;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import com.shengchang.hu.supervision.Adapter.InBouGridAdapter;
import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;

import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.BarcodeCreater;
import com.shengchang.hu.supervision.Utils.BitmapTools;
import com.shengchang.hu.supervision.Utils.BluetoothLeClass;
import com.shengchang.hu.supervision.Utils.Bluetooth_Scale;
import com.shengchang.hu.supervision.Utils.Contants;
import com.shengchang.hu.supervision.Utils.PrividerDialog;
import com.shengchang.hu.supervision.Utils.PubFunction;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import NFC.NdefMessageParser;
import NFC.ParsedNdefRecord;
import Tcp.Tcp_Client;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class InBoundActivity extends BaseActivity implements View.OnClickListener {

    InBoundBar inboundbar;
    TextView Cweghit;
    EditText weightEdit;
    GridView grid;
    TextView keshi;
    Button endShoujiBtn;
    EditText jiaoyanEdit;
    RelativeLayout jiaoyan;
    Button chongfuBtn;


    double plusweight=0;
/*读取IC卡功能*/

    private static final DateFormat TIME_FORMAT = SimpleDateFormat
            .getDateTimeInstance();
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private NdefMessage mNdefPushMessage;
    private android.app.AlertDialog mDialog;

    public static Context context;
    private TextView department_name_text,nurse_name_text,
            medicalwaste_weight_text,collection_time_text,
            tv_dialog_positive,tv_dialog_negative;
    /*打印功能*/
    private String time;
    private String type;
    private String Weigets;
    private String code;
    private String DName;
    Bitmap btMap;
    String   maccode;
    AlertDialog alertDialog;
    boolean isCanPrint = true;
    private PosApi mPosSDK = null;
    private PrintQueue mPrintQueue = null;
    OkHttpClient moKhttpclient = new OkHttpClient();
/*蓝牙设置参数*/
    int BluetoothType=2;
    private Handler mHandler;
    Boolean b_scaleIsConnect=Boolean.FALSE;
    SCALENOW scalenow=new SCALENOW();
    private BluetoothAdapter mBluetoothAdapter;
    final Boolean SendMoudle=true;
    public Bluetooth_Scale btScale=null;
    public BluetoothLeClass bleScale=null;
    Boolean bisClosed=false;
    private EditText  edit;
    private   AlertDialog   dialog;
    private     AlertDialog.Builder  alert;
    private PrividerDialog  prividerDialog;
    //保存数据
    private SharedPreferences settings;
    private SharedPreferences.Editor editorsettings;
    private String departmentid;
    private static final String Nurse_API = Contants.Nurse_API;
    private static final String UP_DATA_API = Contants.UP_DATA_API;
    public int[] icon = {R.drawable.s, R.drawable.g, R.drawable.f, R.drawable.d, R.drawable.h, R.drawable.j

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_bound);
        context = this;
        OutActivity();
        initView();
        ConnectInent();
        //nfc返回的值
        resolveIntent(getIntent());
//        读取nfc
        initReadIC();
//        蓝牙连接
        BleConnction();

        }
    private void BleConnction() {
        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        mHandler=new Handler()
        {
            public void handleMessage(Message msg)
            {
                switch(msg.what)
                {
                    case 2:
                        if(msg.arg1<2) {
                            weightEdit.setText("蓝牙尚未连接");
                            b_scaleIsConnect=Boolean.FALSE;
                        }
                        else {
                            b_scaleIsConnect = Boolean.TRUE;
                            if(SendMoudle)
                            {
                                weightEdit.setText("已连接");
                            }
                        }
                        break;

                }
            }
        };
        mBluetoothAdapter.enable();
        if(btScale==null)btScale = new Bluetooth_Scale(InBoundActivity.this, mHandler);
        btScale.SetOnReceivedDataListener(new Bluetooth_Scale.onReceivedDataListener() {
            @Override
            public void onReceivedData(byte[] buf) {
                OnReceivedData(buf);
            }
        });
        if(bleScale==null)
        {
            bleScale = new BluetoothLeClass(InBoundActivity.this);
            bleScale.initialize();
            bleScale.setOnConnectListener(new BluetoothLeClass.OnConnectListener() {
                @Override
                public void onConnect(BluetoothGatt gatt) {
                    Toast.makeText(InBoundActivity.this,"BLE Connected",Toast.LENGTH_SHORT).show();
                }
            });
            bleScale.setOnDisconnectListener(new BluetoothLeClass.OnDisconnectListener() {
                @Override
                public void onDisconnect(BluetoothGatt gatt) {
                    Toast.makeText(InBoundActivity.this,"BLE Lost",Toast.LENGTH_SHORT).show();
                }
            });
            bleScale.setOnConnectListener(new BluetoothLeClass.OnConnectListener() {
                @Override
                public void onConnect(BluetoothGatt gatt) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(InBoundActivity.this, "蓝牙连接成功", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            });
            bleScale.setOnDisconnectListener(new BluetoothLeClass.OnDisconnectListener() {
                @Override
                public void onDisconnect(BluetoothGatt gatt) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(InBoundActivity.this,"蓝牙没有连接成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
            bleScale.setOnDataAvailableListener(new BluetoothLeClass.OnDataAvailableListener() {
                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

                }

                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    byte[] buffer =characteristic.getValue();
                    OnReceivedData(buffer);
                }
            });
        }

        if(!TextUtils.isEmpty(maccode)&&maccode.length()>0) {
            //ble或者双模模块
            if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                if ((bleScale != null) && bleScale.isConnect) {
                    bleScale.disconnect();
                }
                bleScale.connect(maccode);
                WriteConfig();
            } else {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(maccode);
                if (device != null) {
                    btScale.connect(device);
                    WriteConfig();
                }
            }
        }
        ReadConfig();
        if(maccode.length()>0) {
            //ble或者双模模块
            if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                if ((bleScale != null) && bleScale.isConnect) {
                    bleScale.disconnect();
                }
                bleScale.connect(maccode);
            } else {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(maccode);
                if (device != null) {
                    btScale.connect(device);
                }
            }
        }



    }
    private void initReadIC() {
        mDialog = new android.app.AlertDialog.Builder(this).setNeutralButton("Ok", null)
                .create();

        // 获取默认的NFC控制器
        mAdapter = NfcAdapter.getDefaultAdapter(this);

        //拦截系统级的NFC扫描，例如扫描蓝牙
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord("",
                Locale.ENGLISH, true) });
    }

    @Override
    protected void onResume() {
        super.onResume();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            initPos();

                        }
                    });
                } catch (InputMismatchException e) {
                    e.printStackTrace();
                }

            }
        }).start();
        if (mAdapter == null) {
            if (!mAdapter.isEnabled()) {
                showWirelessSettingsDialog();
            }

            showMessage("error", " NO NFC");
            showShortToast("设备不支持NFC");


            return;
        }
        if (!mAdapter.isEnabled()) {
            showShortToast("请在系统设置中先启用NFC功能");

            return;
        }

        if (mAdapter != null) {
            //隐式启动
            mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
            mAdapter.enableForegroundNdefPush(this, mNdefPushMessage);
        }

    }

    private void initPos() {
        // 获取PosApi实例
        mPosSDK = PosApi.getInstance(this);
        // 根据型号进行初始化mPosApi类
        if (Build.MODEL.contains("LTE")
                || Build.DISPLAY.contains("3508")
                || Build.DISPLAY.contains("403")
                || Build.DISPLAY.contains("35S09")) {
            mPosSDK.initPosDev("ima35s09");
        } else if (Build.MODEL.contains("5501")) {
            mPosSDK.initPosDev("ima35s12");
        } else {
            mPosSDK.initPosDev(PosApi.PRODUCT_MODEL_IMA80M01);
        }

        //监听初始化回调结果
        mPosSDK.setOnComEventListener(mCommEventListener);
        // 打印队列初始化
        mPrintQueue = new PrintQueue(this, mPosSDK);
        // 打印队列初始化
        mPrintQueue.init();
        //打印队列设置监听
        mPrintQueue.setOnPrintListener(new PrintQueue.OnPrintListener() {
            //打印完成
            @Override
            public void onFinish() {
                // TODO Auto-generated method stub
                //打印完成
                dismissProgressDialog();
                Toast.makeText(getApplicationContext(),
                        getString(R.string.print_complete), Toast.LENGTH_SHORT)
                        .show();
                //当前可打印
                isCanPrint = true;
                //完成之后关掉打印功能
//
            }

            //打印失败
            @Override
            public void onFailed(int state) {
                // TODO Auto-generated method stub
                isCanPrint = true;
                switch (state) {
                    case PosApi.ERR_POS_PRINT_NO_PAPER:
                        // 打印缺纸
                        dismissProgressDialog();
                        showTipDialog(getString(R.string.print_no_paper));
                        break;
                    case PosApi.ERR_POS_PRINT_FAILED:
                        // 打印失败
                        dismissProgressDialog();
                        showTipDialog(getString(R.string.print_failed));
                        break;
                    case PosApi.ERR_POS_PRINT_VOLTAGE_LOW:
                        // 电压过低
                        dismissProgressDialog();
                        showTipDialog(getString(R.string.print_voltate_low));
                        break;
                    case PosApi.ERR_POS_PRINT_VOLTAGE_HIGH:
                        // 电压过高
                        dismissProgressDialog();
                        showTipDialog(getString(R.string.print_voltate_high));
                        break;
                }
            }

            @Override
            public void onGetState(int arg0) {
                // TODO Auto-generated method stub

            }

            //打印设置
            @Override
            public void onPrinterSetting(int state) {
                // TODO Auto-generated method stub
                isCanPrint = true;
                switch (state) {
                    case 0:
                        Toast.makeText(InBoundActivity.this, "持续有纸", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        //缺纸
                        Toast.makeText(InBoundActivity.this, getString(R.string.no_paper), Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        //检测到黑标
                        Toast.makeText(InBoundActivity.this, getString(R.string.label), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    private void showMessage(String title, String message) {
        mDialog.setTitle(title);
        mDialog.setMessage(message);
        mDialog.show();
    }

    private NdefRecord newTextRecord(String text, Locale locale,
                                     boolean encodeInUtf8) {
        byte[] langBytes = locale.getLanguage().getBytes(
                Charset.forName("US-ASCII"));

        Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset
                .forName("UTF-16");
        byte[] textBytes = text.getBytes(utfEncoding);

        int utfBit = encodeInUtf8 ? 0 : (1 << 7);
        char status = (char) (utfBit + langBytes.length);

        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        data[0] = (byte) status;
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
                textBytes.length);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                new byte[0], data);
    }

    private void showWirelessSettingsDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setMessage("nfc_disabled");
        builder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(
                                Settings.ACTION_WIRELESS_SETTINGS);
                        startActivity(intent);
                    }
                });
        builder.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
        builder.create().show();
        return;
    }

    /**
     * 初始化
     */
    OnCommEventListener mCommEventListener = new OnCommEventListener() {
        @Override
        public void onCommState(int cmdFlag, int state, byte[] resp, int respLen) {
            // TODO Auto-generated method stub
            switch (cmdFlag) {
                case PosApi.POS_INIT:
                    if (state == PosApi.COMM_STATUS_SUCCESS) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showShortToast("设备初始化成功");
                            }
                        });

                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showShortToast("设备初始化失败");
                            }
                        });
                    }
                    break;
            }
        }
    };

    //打印
    private void Pos() {
        try {
            StringBuilder sb = new StringBuilder();
//            sb.append("        安庆市立医院医废信息   ");
            sb.append(getString(R.string.hostptelname));
//            sb.append("        启东合作镇卫生院    ");
//            sb.append("       乌鲁木齐国际医院   ");
//            sb.append("        启东城区医院     ");

//            sb.append("       盐城响水县人民医院   ");
            sb.append("\n");
            sb.append("-----------------------------");
            sb.append("\n");
            sb.append("重量: " + Weigets + "kg");
            sb.append("    ");
            sb.append("类型: " + type);
            sb.append("\n");
            sb.append("收集人: " + App.getApp().getName());
            sb.append("   ");
            sb.append("校验人: " + jiaoyanEdit.getText().toString());
            sb.append("\n");
            sb.append("科室: " + DName);
            sb.append("\n");
            sb.append("时间: " + time);

            sb.append("\n");
            sb.append("编码: "+code);
            sb.append("\n");
            byte[] bt = sb.toString().getBytes("GBK");
            btMap = BarcodeCreater.creatBarcode(this, code.trim(), 380, 100,
                    true, 1);
//            btMap = encode2dAsBitmap(code.trim(), 260, 300, 2);
            byte[] printData = BitmapTools.bitmap2PrinterBytes(btMap);

            mPosSDK.printText(60, bt, bt.length);
            sb.append("              ");
            sb.append("\n");
            sb.append("\n");
            sb.append("\n");
            sb.append("\n");
            sb.append("\n");
            // 将打印数组添加到打印队列
            mPrintQueue.addBmp(60, 40, btMap.getWidth(), btMap.getHeight(),
                    printData);
            mPrintQueue.addText(50, "\n\n".getBytes("GBK"));


        } catch (
                UnsupportedEncodingException e)

        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mPrintQueue.printStart();

    }

    //打印
    private void Pos1() {
        SharedPreferences settings = getSharedPreferences("preferences_settings",0);
        try {
            StringBuilder sb = new StringBuilder();
//            sb.append("    安庆市立医院医废信息     ");
            sb.append(getString(R.string.hostptelname));
//            sb.append("        启东合作镇卫生院    ");
//            sb.append("       乌鲁木齐国际医院   ");
//            sb.append("        启东城区医院     ");

//            sb.append("       盐城响水县人民医院   ");
            sb.append("\n");
            sb.append("-----------------------------");
            sb.append("\n");
            sb.append("重量: " + settings.getString("weight","") + "kg");
            sb.append("    ");
            sb.append("类型: " + settings.getString("type",""));
            sb.append("\n");
            sb.append("收集人: " + settings.getString("shoujiren",""));
            sb.append("   ");
            sb.append("校验人: " + settings.getString("jiaoyanren",""));
            sb.append("\n");
            sb.append("科室: " + settings.getString("departmentName",""));
            sb.append("\n");
            sb.append("时间: " + settings.getString("upTime",""));

            sb.append("\n");
            sb.append("编码: "+settings.getString("rubbishCode",""));
            sb.append("\n");
            byte[] bt = sb.toString().getBytes("GBK");
            btMap = BarcodeCreater.creatBarcode(this, settings.getString("rubbishCode","").trim(), 380, 100,
                    true, 1);
//            btMap = encode2dAsBitmap(code.trim(), 260, 300, 2);
            byte[] printData = BitmapTools.bitmap2PrinterBytes(btMap);

            mPosSDK.printText(60, bt, bt.length);
            sb.append("              ");
            sb.append("\n");
            sb.append("\n");
            sb.append("\n");
            sb.append("\n");
            sb.append("\n");
            // 将打印数组添加到打印队列
            mPrintQueue.addBmp(60, 40, btMap.getWidth(), btMap.getHeight(),
                    printData);
            mPrintQueue.addText(50, "\n\n".getBytes("GBK"));


        } catch (
                UnsupportedEncodingException e)

        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mPrintQueue.printStart();

    }

    public static Bitmap encode2dAsBitmap(String contents, int desiredWidth,
                                          int desiredHeight, int barType) {
        BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;
        if (barType == 1) {
            barcodeFormat = BarcodeFormat.CODE_128;
        } else if (barType == 2) {
            barcodeFormat = BarcodeFormat.QR_CODE;
        }

        Bitmap barcodeBitmap = null;
        try {
            barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,
                    desiredWidth, desiredHeight);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return barcodeBitmap;
    }

    public static Bitmap encodeAsBitmap(String contents, BarcodeFormat format,
                                        int desiredWidth, int desiredHeight) throws WriterException {
        final int WHITE = 0xFFFFFFFF;
        final int BLACK = 0xFF000000;

        HashMap<EncodeHintType, String> hints = null;
        String encoding = guessAppropriateEncoding(contents);
        if (encoding != null) {
            hints = new HashMap<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, encoding);
        }
        MultiFormatWriter writer = new MultiFormatWriter();
        BitMatrix result = writer.encode(contents, format, desiredWidth,
                desiredHeight, hints);
        result = deleteWhite(result);// 删除白边
        int width = result.getWidth();
        int height = result.getHeight();
        int[] pixels = new int[width * height];
        // All are 0, or black, by default
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    public static String guessAppropriateEncoding(CharSequence contents) {
        // Very crude at the moment
        for (int i = 0; i < contents.length(); i++) {
            if (contents.charAt(i) > 0xFF) {
                return "UTF-8";
            }
        }
        return null;
    }


    private void initView() {
        Cweghit=findViewById(R.id.Cweghit);
        weightEdit=findViewById(R.id.weight_edit);
        grid=findViewById(R.id.grid);
        keshi=findViewById(R.id.keshi);
        endShoujiBtn=findViewById(R.id.end_shouji_btn);
        endShoujiBtn.setOnClickListener(this);
        jiaoyanEdit=findViewById(R.id.jiaoyan_edit);
        jiaoyan=findViewById(R.id.jiaoyan);
        chongfuBtn=findViewById(R.id.chongfu_btn);
        chongfuBtn.setOnClickListener(this);
        settings = getSharedPreferences("preferences_settings",Context.MODE_PRIVATE);
        editorsettings = settings.edit();
        grid.setAdapter(new InBouGridAdapter(this));
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (icon[position]) {
                    //感染
                    case R.drawable.s:

                        final String str1 = "831-001-01";
                        InitAlert(str1);
//                        Posrequest(str1);
                        break;
                    //损伤类
                    case R.drawable.g:
                        final String str = "831-002-01";
                        InitAlert(str);
//                        Posrequest(str);
                        break;
                    //病理类
                    case R.drawable.f:
                        final String str6= "831-003-01";
                        InitPasswordAlert(str6);
//                        InitAlert(str6);
//                        Posrequest(str6);

//                        showShortToast("暂无此类型医废");
                        break;
                    //化学类
                    case R.drawable.d:
                        final String str5 = "831-005-01";
                        InitPasswordAlert(str5);
//                        InitAlert(str5);
//                        Posrequest(str5);


//                        showShortToast("暂无此类型医废");
                        break;
                    //药物类
                    case R.drawable.h:
                        final  String str3 = "831-004-01";
                        InitPasswordAlert(str3);
//                        InitAlert(str3);
//                        showShortToast("暂无此类型医废");

                        break;
                    //输液袋
                    case R.drawable.j:
//                        final String str4= "831-002-02";
//                        Posrequest(str4);
                        showShortToast("暂无此类型医废");
                        break;

                }
            }
        });
        //妇幼保健院用
//        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                switch (icon[position]) {
//                    //感染
//                    case R.drawable.s:
//
//                        final String str1 = "831-001-01";
//                        InitAlert(str1);
////                        Posrequest(str1);
//                        break;
//                    //损伤类
//                    case R.drawable.g:
//                        final String str = "831-002-01";
//                        InitAlert(str);
////                        Posrequest(str);
//                        break;
//                    //病理类
//                    case R.drawable.f:
//                        final String str6= "831-003-01";
//                        InitAlert(str6);
////                        Posrequest(str6);
//
////                        showShortToast("暂无此类型医废");
//                        break;
//                    //药物类
//                    case R.drawable.d:
//                        final String str5 = "831-005-01";
//                        InitAlert(str5);
////                        Posrequest(str5);
//
//
////                        showShortToast("暂无此类型医废");
//                        break;
//                    //新冠感染类
//                    case R.drawable.h:
//                        final  String str3 = "831-001-02";
//                        InitAlert(str3);
////                        showShortToast("暂无此类型医废");
//
//                        break;
//                    //新冠损伤类
//                    case R.drawable.j:
//                        final String str4= "831-002-02";
//                        InitAlert(str4);
////                        showShortToast("暂无此类型医废");
//                        break;
//
//                }
//            }
//        });

    }

    private void InitPasswordAlert(final String Westcode) {
        alert=new AlertDialog.Builder(InBoundActivity.this);

        LayoutInflater inflater = (LayoutInflater) InBoundActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.initpasswordedit, null);
         edit=view.findViewById(R.id.editText2);
        tv_dialog_positive=view.findViewById(R.id.tv_dialog_positive);

        tv_dialog_negative=view.findViewById(R.id.tv_dialog_negative);

         alert.setView(view);
         alert.setTitle("请输入密码");

         dialog= alert.show();

        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                            s=edit.getText().toString();
                if (!s.toString().equals("9876") &&  s.length()==4){
                    dialog.dismiss();
                    showShortToast("密码错误");

                }else if (s.toString().equals("9876")){
                    showShortToast("密码正确");
                    tv_dialog_positive.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Posrequest(Westcode);
                        }
                    });
                    tv_dialog_negative.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                }
                }

            @Override
            public void afterTextChanged(final Editable s) {



    }
});

    }

    private void InitAlert(final String  Westcode) {
        String   strcode = null;
        if (Westcode.equals("831-001-02")){
            strcode="新冠感染类";

        }else if (Westcode.equals("831-002-02")){
            strcode="新冠损伤类";
        }else if (Westcode.equals("831-001-01")){
            strcode="感染类";
        }else if (Westcode.equals("831-002-01")){
            strcode="损伤类";
        }else if (Westcode.equals("831-003-01")){
            strcode="病理类";
        }else if (Westcode.equals("831-005-01")){
            strcode="药物类";
        }else if (Westcode.equals("831-004-01")){
            strcode="化学类";
        }
        prividerDialog = new PrividerDialog(InBoundActivity.this,
                "提示", "确定是否选择"+strcode, "确定", "取消",
                new com.shengchang.hu.supervision.Utils.AlertDialog.OnDialogButtonClickListener() {
                    @Override
                    public void onDialogButtonClick(boolean isPositive) {
                        if (isPositive) {
                            Posrequest(Westcode);
                        } else {


                        }
                    }
                });
        if (!InBoundActivity.this.isFinishing()) {
            prividerDialog.show();
        }


    }
    private void Posrequest(final String string) {
        if (TextUtils.isEmpty(keshi.getText().toString())) {
            showShortToast("科室不能为空");
        } else if (TextUtils.isEmpty(jiaoyanEdit.getText().toString())) {
            showShortToast("护士校验不能为空");
        } else if (TextUtils.isEmpty(weightEdit.getText().toString())) {
            showShortToast("重量不能为空");
        } else {
            showProgressDialog();
            new Thread(new Runnable() {
                @Override

                public void run() {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            PostRequest(string);

                        }
                    });
                }
            }).start();
        }
    }

    private void PostRequest(String string) {
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("typeCode", string)
                .add("weight", weightEdit.getText().toString())
                .add("handoverName", jiaoyanEdit.getText().toString())
                .add("departmentId", departmentid)
                .build();
        Request request = new Request.Builder()
                .url(UP_DATA_API)
                .post(formBody)
                .build();
        Log.d("UP_DATA_API", UP_DATA_API + "?id=" + App.getApp().getToken()
                + "&typeCode=" + string
                + "&weight=" + weightEdit.getText().toString()
                + "&handoverName=" + jiaoyanEdit.getText().toString()
                + "&departmentId=" + departmentid);
        Call call = moKhttpclient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String Poststr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PostRespomse(Poststr);
                    }
                });


            }
        });

    }

    private void PostRespomse(String poststr) {
        try {
            JSONObject mJson = new JSONObject(poststr);
            String msg = mJson.getString("message");
            if (msg.equals("20004")) {
                dismissProgressDialog();
                showShortToast("网络异常");
            } else if (msg.equals("20005")) {
                dismissProgressDialog();
                Handler mhandle = new Handler();
                mhandle.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showProgressDialog();
                        Pos();
                    }
                }, 20);
            } else if (msg.equals("20017")) {
                dismissProgressDialog();
                showShortToast("重量小于等于零");
            }else if (msg.equals("20006")){
                dismissProgressDialog();
                showShortToast("医废已上传");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            JSONObject datajson = new JSONObject(poststr);
            JSONObject rubbish = datajson.getJSONObject("rubbish");
            type = rubbish.getString("type");
            time = rubbish.getString("upTime");
            code = rubbish.getString("rubbishCode");
            Weigets = rubbish.getString("weight");
            plusweight=plusweight+Double.parseDouble(Weigets);
            DName = rubbish.getString("departmentName");
            editorsettings.putString("type", type);
            editorsettings.putString("upTime", time);
            editorsettings.putString("rubbishCode", code);
            editorsettings.putString("weight", Weigets);
            editorsettings.putString("departmentName", DName);
            editorsettings.putString("jiaoyanren", jiaoyanEdit.getText().toString());
            editorsettings.putString("shoujiren", App.getApp().getName());
            editorsettings.commit();

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    private void OutActivity() {
        inboundbar=findViewById(R.id.inboundbar);
        inboundbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void ConnectInent() {
        Intent intent = getIntent();

        String ufhdata = intent.getStringExtra("Ufhdata");
        departmentid = intent.getStringExtra("departmentid");
        maccode=intent.getStringExtra("maccode");
        Log.d("departmentid", departmentid);
        keshi.setText(ufhdata);

    }


//初步判断是什么类型NFC卡
private void resolveIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        Parcelable[] rawMsgs = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage[] msgs;
        if (rawMsgs != null) {
            msgs = new NdefMessage[rawMsgs.length];
            for (int i = 0; i < rawMsgs.length; i++) {
                msgs[i] = (NdefMessage) rawMsgs[i];
            }
        } else {
            // Unknown tag type
            byte[] empty = new byte[0];
            byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            Parcelable tag = intent
                    .getParcelableExtra(NfcAdapter.EXTRA_TAG);
            byte[] payload = dumpTagData(tag).getBytes();
            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
                    empty, id, payload);
            NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
            msgs = new NdefMessage[] { msg };
        }
        // Setup the views

//        showShortToast("");
        buildTagViews(msgs);
    }
}

    //一般公家卡，扫描的信息
    private String dumpTagData(Parcelable p) {
        StringBuilder sb = new StringBuilder();
        Tag tag = (Tag) p;
        byte[] id = tag.getId();
        sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
        sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
        sb.append("ID (reversed): ").append(getReversed(id)).append("\n");

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }
        sb.delete(sb.length() - 2, sb.length());
        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('\n');
                MifareClassic mifareTag = MifareClassic.get(tag);
                String type = "Unknown";
                switch (mifareTag.getType()) {
                    case MifareClassic.TYPE_CLASSIC:
                        type = "Classic";
                        break;
                    case MifareClassic.TYPE_PLUS:
                        type = "Plus";
                        break;
                    case MifareClassic.TYPE_PRO:
                        type = "Pro";
                        break;
                }
                sb.append("Mifare Classic type: ");
                sb.append(type);
                sb.append('\n');

                sb.append("Mifare size: ");
                sb.append(mifareTag.getSize() + " bytes");
                sb.append('\n');

                sb.append("Mifare sectors: ");
                sb.append(mifareTag.getSectorCount());
                sb.append('\n');

                sb.append("Mifare blocks: ");
                sb.append(mifareTag.getBlockCount());
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('\n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }

        return sb.toString();
    }

    private String getHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private long getReversed(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = bytes.length - 1; i >= 0; --i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    //显示NFC扫描的数据
    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) {
            return;
        }
        Date now = new Date();
        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
        final int size = records.size();
        for (int i = 0; i < size; i++) {
            TextView timeView = new TextView(this);
            timeView.setText(TIME_FORMAT.format(now));
            ParsedNdefRecord record = records.get(i);

//            showShortToast(String.valueOf(record.getViewText()));
            String viewText = record.getViewText();
            String[] split = viewText.split("\\n");
            String[] split2 = split[1].split(" ");
            final String string = split2[3];

            if (!TextUtils.isEmpty(string)  && string.length()>9){

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        Handler handler = new Handler(Looper.getMainLooper());
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        showProgressDialog();
                                        NurseRequest(string);

                                    }
                                });


                            }
                            }).start();

            }else  if(!TextUtils.isEmpty(string)  && string.length()<=9){
                final   String  s="0"+string;
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                showProgressDialog();
                                NurseRequest(s);

                            }
                        });


                    }
                }).start();

            }else{
                showShortToast("读卡失败，请重新读");
            }

//            jiaoyanEdit.setText(string);

            Log.d("record", String.valueOf(string));
        }
    }

    //获取系统隐式启动的
    @Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        resolveIntent(intent);
    }

    private void NurseRequest(String epcStr) {
        OkHttpClient moKhttp = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("cardCode", epcStr)
                .build();
        Request request = new Request.Builder()
                .url(Nurse_API)
                .post(formBody)
                .build();
        Log.d("Nurse_API", Nurse_API + "?id=" + App.getApp().getToken() + "&cardCode=" + epcStr);
        Call call = moKhttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String nursestr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        NurseResponse(nursestr);
                    }
                });
            }
        });


    }

    private void NurseResponse(String nursestr) {
        try {
            JSONObject NurseJson = new JSONObject(nursestr);
            String NurseMsg = NurseJson.getString("message");
            if (NurseMsg.equals("20005")) {
                dismissProgressDialog();

            } else if (NurseMsg.equals("20008")) {
                dismissProgressDialog();
                showShortToast("查无此卡");
            } else if (NurseMsg.equals("20009")) {
                dismissProgressDialog();
                showShortToast("类型不符");
            } else if (NurseMsg.equals("20015")) {
                dismissProgressDialog();
                showShortToast("产生点不符");
            } else if (NurseMsg.equals("20019")) {
                dismissProgressDialog();
                showShortToast("卡片未分配");
            } else if (NurseMsg.equals("20020")) {
                dismissProgressDialog();
                showShortToast("上步操作未完成");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject NusrseData = new JSONObject(nursestr);
            String handoverName = NusrseData.getString("handoverName");
            jiaoyanEdit.setText(handoverName);
            if (!TextUtils.isEmpty(jiaoyanEdit.getText().toString())) {

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



    byte[] strdata=new byte[100];
    int pStrdata=0;
    void OnReceivedData(byte buf[])
    {
        int bytes=buf.length;
        for(int i = 0; i < bytes; i++)
        {
            if(buf[i]==0x2)pStrdata=0;
            else  if((buf[i]==0x0a)||(buf[i]==0x03))
            {
                GetWeight(strdata,pStrdata);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                        if(scalenow.bOverFlag)
                        {
                            weightEdit.setText("over----");
                        }
                        else {
                            weightEdit.setText(scalenow.sformatNetWeight);
                            Log.d("ueiwooss", weightEdit.getText().toString());
                        }

                    }
                });

                pStrdata=0;
            }
            else
            {
                strdata[pStrdata] = buf[i];
                if(++pStrdata>=100)pStrdata=0;
            }
        }
    }

    void GetWeight(byte[] databuf,int datalenght)
    {
        float f=0;
        int dot=1;
        scalenow.bOverFlag=false;
        scalenow.bWeiStaFlag=false;
        switch(databuf[0])
        {
            case 'o':
            case 'O':
                scalenow.bOverFlag=true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag=false;
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag=true;
                break;
        }
        if(datalenght>7) {
            for(int i=0;i<7;i++) {
                if (databuf[i + 6 + 1] == '.') {
                    dot = -1;
                } else {
                    if (dot >= 0) {
                        f = f * 10 + ((databuf[i + 6 + 1] == ' ') ? 0 : (databuf[i + 6 + 1] - '0'));
                    } else {
                        f += Math.pow(10, dot) * (databuf[i + 6 + 1] - '0');
                        dot--;
                    }
                }
            }
            if (databuf[6] == '-') f *= -1;
        }
        if(dot<0)dot=(-dot)-1;
        else dot=0;
        scalenow.fformatNetWeight=f;
        scalenow.sformatNetWeight=String.format("%1."+String.valueOf(dot)+"f",f);
        if(datalenght>14)
        {
            scalenow.sUnit=new String(databuf,14,datalenght-14);
        }
        scalenow.bZeroFlag=(f==0);
    }
    public void ReadConfig() {
        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, Context.MODE_PRIVATE);
        maccode = settings.getString("BluetoothAddress", "");
        BluetoothType = settings.getInt("BluetoothType", 0);
    }
    public void WriteConfig()
    {

        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("BluetoothType", BluetoothType);
        editor.putString("BluetoothAddress", maccode);
        editor.commit();
    }

    public static class SCALENOW {
        public String sformatNetWeight="0";
        public String sUnit=" g ";
        public float fformatNetWeight;
        public boolean bZeroFlag;
        public boolean bWeiStaFlag;
        public boolean bOverFlag;
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.end_shouji_btn:
                   InnitAlert();
//                Intent intent = new Intent(InBoundActivity.this, KeshiActivity.class);
//                intent.putExtra("departmentid",departmentid);
//                startActivity(intent);
//                finish();
                break;
            case R.id.chongfu_btn:
                if (departmentid.toString()==null){
                    showShortToast("请先选择类型打印");
                }else{
                    Handler mhandle = new Handler();
                    mhandle.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showProgressDialog();
                            Pos1();
                        }
                    }, 20);
                }

                break;


        }
    }
    private void InnitAlert() {

        Date date = new Date();
        String time = date.toLocaleString();
        Log.i("md", "时间time为： "+time);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
        String sim = dateFormat.format(date);
        final AlertDialog.Builder dialog = new AlertDialog.Builder(InBoundActivity.this);
        View view = LayoutInflater.from(this.getBaseContext()).inflate(R.layout.census_dialog_layout,null,false);
        dialog.setView(view);
        department_name_text=view.findViewById(R.id.department_name);
        department_name_text.setText(keshi.getText().toString());
        nurse_name_text=view.findViewById(R.id.nurse_name);
        nurse_name_text.setText(jiaoyanEdit.getText().toString());
        collection_time_text=view.findViewById(R.id.collection_time);
        collection_time_text.setText(sim);
        medicalwaste_weight_text=view.findViewById(R.id.medicalwaste_weight);
        medicalwaste_weight_text.setText(String.valueOf(plusweight)+"   kg");
        tv_dialog_positive=view.findViewById(R.id.tv_dialog_positive);
        tv_dialog_positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                plusweight=0;
                InBoundActivity.this.finish();
            }
        });
        tv_dialog_negative=view.findViewById(R.id.tv_dialog_negative);
        tv_dialog_negative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
        dialog.show();

}
    @Override
    protected void onPause() {

        super.onPause();
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }

        if (mAdapter != null) {
            //隐式启动
            mAdapter.disableForegroundDispatch(this);
            mAdapter.disableForegroundNdefPush(this);
        }

        if (mPrintQueue != null) {
            // 打印队列关闭
            mPrintQueue.close();
        }

        // 关闭下层串口以及打印机
        mPosSDK.closeDev();


    }


    @Override
    protected void onDestroy() {
        if (btScale != null) btScale.stop();
        bisClosed=true;
        super.onDestroy();


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
